<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时翻译工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        neutral: '#64748B',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-height {
                transition: height 0.3s ease;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <header class="text-center mb-10">
            <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-gray-800 mb-2">
                <i class="fa fa-language text-primary mr-3"></i>实时翻译工具
            </h1>
            <p class="text-neutral text-lg">通过WebSocket实现的实时翻译服务</p>
        </header>
        
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6 transform transition-all duration-300 hover:shadow-xl">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 源文本区域 -->
                <div>
                    <label for="sourceText" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fa fa-pencil-square-o mr-1"></i>源文本
                    </label>
                    <div class="relative">
                        <textarea id="sourceText" 
                                  class="w-full h-48 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all resize-none"
                                  placeholder="请输入要翻译的文本..."></textarea>
                        <button id="clearSourceBtn" class="absolute right-3 bottom-3 text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fa fa-times-circle"></i>
                        </button>
                    </div>
                    <div class="mt-2 text-right text-sm text-gray-500">
                        <span id="charCount">0</span> 字符
                    </div>
                </div>
                
                <!-- 翻译结果区域 -->
                <div>
                    <label for="resultText" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fa fa-check-square-o mr-1"></i>翻译结果
                    </label>
                    <div class="relative">
                        <textarea id="resultText" 
                                  class="w-full h-48 p-3 border border-gray-300 rounded-lg bg-gray-50 focus:ring-2 focus:ring-primary focus:border-primary transition-all resize-none"
                                  readonly placeholder="翻译结果将显示在这里..."></textarea>
                        <button id="copyResultBtn" class="absolute right-3 bottom-3 text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-copy"></i>
                        </button>
                    </div>
                    <div id="copyNotification" class="hidden mt-2 text-right text-sm text-secondary">
                        <i class="fa fa-check mr-1"></i>已复制到剪贴板
                    </div>
                </div>
            </div>
            
            <!-- 语言选择和控制区域 -->
            <div class="mt-6 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div class="flex items-center gap-3 w-full sm:w-auto">
                    <select id="fromLanguage" class="flex-1 sm:flex-none px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                        <option value="auto">自动检测</option>
                        <option value="zh">中文</option>
                        <option value="en">英语</option>
                        <option value="ja">日语</option>
                        <option value="ko">韩语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="ru">俄语</option>
                        <option value="es">西班牙语</option>
                    </select>
                    
                    <button id="swapLanguages" class="p-2 rounded-full border border-gray-300 hover:bg-gray-100 transition-colors">
                        <i class="fa fa-exchange text-gray-600"></i>
                    </button>
                    
                    <select id="toLanguage" class="flex-1 sm:flex-none px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                        <option value="en">英语</option>
                        <option value="zh">中文</option>
                        <option value="ja">日语</option>
                        <option value="ko">韩语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="ru">俄语</option>
                        <option value="es">西班牙语</option>
                    </select>
                </div>
                
                <button id="translateBtn" class="w-full sm:w-auto bg-primary hover:bg-primary/90 text-white font-medium px-6 py-2 rounded-lg transition-all flex items-center justify-center gap-2">
                    <i class="fa fa-language"></i>
                    <span>开始翻译</span>
                </button>
            </div>
        </div>
        
        <!-- 连接状态指示 -->
        <div id="connectionStatus" class="bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded mb-6 flex items-center">
            <i class="fa fa-circle-o-notch fa-spin text-yellow-500 mr-3 text-xl"></i>
            <span>正在连接到翻译服务...</span>
        </div>
        
        <footer class="text-center text-gray-500 text-sm mt-10">
            <p>© 2023 实时翻译工具 | 使用WebSocket和百度翻译API构建</p>
        </footer>
    </div>

    <script>
        // DOM元素
        const sourceText = document.getElementById('sourceText');
        const resultText = document.getElementById('resultText');
        const fromLanguage = document.getElementById('fromLanguage');
        const toLanguage = document.getElementById('toLanguage');
        const translateBtn = document.getElementById('translateBtn');
        const clearSourceBtn = document.getElementById('clearSourceBtn');
        const copyResultBtn = document.getElementById('copyResultBtn');
        const copyNotification = document.getElementById('copyNotification');
        const swapLanguages = document.getElementById('swapLanguages');
        const charCount = document.getElementById('charCount');
        const connectionStatus = document.getElementById('connectionStatus');
        
        // WebSocket连接
        let socket;
        let isConnected = false;
        
        // 更新连接状态显示
        const updateConnectionStatus = (status, isError = false) => {
            if (status === 'connecting') {
                connectionStatus.className = 'bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded mb-6 flex items-center';
                connectionStatus.innerHTML = '<i class="fa fa-circle-o-notch fa-spin text-yellow-500 mr-3 text-xl"></i><span>正在连接到翻译服务...</span>';
                isConnected = false;
            } else if (status === 'connected') {
                connectionStatus.className = 'bg-green-50 border-l-4 border-green-400 p-4 rounded mb-6 flex items-center';
                connectionStatus.innerHTML = '<i class="fa fa-check-circle text-green-500 mr-3"></i><span>已连接到翻译服务</span>';
                isConnected = true;
            } else if (status === 'error') {
                connectionStatus.className = 'bg-red-50 border-l-4 border-red-400 p-4 rounded mb-6 flex items-center';
                connectionStatus.innerHTML = '<i class="fa fa-exclamation-circle text-red-500 mr-3"></i><span>连接失败，请刷新页面重试</span>';
                isConnected = false;
            } else if (status === 'translating') {
                connectionStatus.className = 'bg-blue-50 border-l-4 border-blue-400 p-4 rounded mb-6 flex items-center';
                connectionStatus.innerHTML = '<i class="fa fa-circle-o-notch fa-spin text-blue-500 mr-3 text-xl"></i><span>正在翻译...</span>';
            }
        };
        
        // 连接WebSocket
        const connectWebSocket = () => {
            updateConnectionStatus('connecting');
            
            try {
                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const host = window.location.host;
                socket = new WebSocket(`${protocol}//${host}/translate`);
                
                socket.onopen = () => {
                    updateConnectionStatus('connected');
                };
                
                socket.onmessage = (event) => {
                    updateConnectionStatus('connected');
                    const response = JSON.parse(event.data);
                    
                    if (response.success) {
                        resultText.value = response.translatedText;
                    } else {
                        resultText.value = `翻译失败: ${response.errorMessage}`;
                    }
                };
                
                socket.onclose = () => {
                    updateConnectionStatus('connecting');
                    // 尝试重连
                    setTimeout(connectWebSocket, 3000);
                };
                
                socket.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    updateConnectionStatus('error', true);
                };
            } catch (error) {
                console.error('连接WebSocket失败:', error);
                updateConnectionStatus('error', true);
            }
        };
        
        // 发送翻译请求
        const sendTranslationRequest = () => {
            const text = sourceText.value.trim();
            
            if (!text) {
                alert('请输入要翻译的文本');
                return;
            }
            
            if (!isConnected) {
                alert('尚未连接到翻译服务，请稍候重试');
                return;
            }
            
            updateConnectionStatus('translating');
            
            const request = {
                text: text,
                fromLanguage: fromLanguage.value,
                toLanguage: toLanguage.value
            };
            
            socket.send(JSON.stringify(request));
        };
        
        // 事件监听
        translateBtn.addEventListener('click', sendTranslationRequest);
        
        clearSourceBtn.addEventListener('click', () => {
            sourceText.value = '';
            charCount.textContent = '0';
        });
        
        copyResultBtn.addEventListener('click', () => {
            if (resultText.value) {
                resultText.select();
                document.execCommand('copy');
                
                copyNotification.classList.remove('hidden');
                setTimeout(() => {
                    copyNotification.classList.add('hidden');
                }, 2000);
            }
        });
        
        swapLanguages.addEventListener('click', () => {
            if (fromLanguage.value !== 'auto') {
                const temp = fromLanguage.value;
                fromLanguage.value = toLanguage.value;
                toLanguage.value = temp;
            }
        });
        
        sourceText.addEventListener('input', () => {
            charCount.textContent = sourceText.value.length;
        });
        
        // 按Enter键翻译，Shift+Enter换行
        sourceText.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendTranslationRequest();
            }
        });
        
        // 初始化连接
        connectWebSocket();
    </script>
</body>
</html>
